package com.yuntuzhilian.chapter5.demo4;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author MrWang-shuizhishuiheshui
 * @description
 */
public class FaSongFang {
    public static void main(String[] args) {
        DatagramSocket ds=null;
        try {
            String str="你好,这款产品怎么样?";
            System.out.println("发送方:"+str);

            //获取本地主机地址
            InetAddress id=InetAddress.getByName("localhost");
            //创建数据报
            DatagramPacket dpOut=new DatagramPacket(
                    str.getBytes(),str.getBytes().length,
                    id,8800);
            //创建站点
            ds=new DatagramSocket();
            //站点对象发送数据报
            ds.send(dpOut);


            //接收
            byte[] bytes=new byte[1024];
            DatagramPacket dpIn=new DatagramPacket(bytes,bytes.length);
            ds.receive(dpIn);
            //显示数据
            String str1=new String(dpIn.getData(),0,dpIn.getLength());
            //dpIn.getAddress().getHostAddress() : 从数据报中拿到发送者的地址,并取出ip
            System.out.println(dpIn.getAddress().getHostAddress()+"说:"+str1);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ds.close();
        }

    }
}
